package com.springbootweb.controller;

import com.codingapi.txlcn.tc.annotation.DTXPropagation;
import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.springbootproduct.entity.Product;
import com.springbootweb.client.OrderClient;
import com.springbootorder.entity.Order;
import com.springbootweb.client.ProductClient;
//import com.springbootweb.common.Sender;
import com.springbootweb.common.UuidUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

@Api(description = "订单控制器")
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderClient orderClient;
    @Autowired
    private ProductClient productClient;
//    @Autowired
//    Sender sender;

    @ApiOperation(value = "查询订单列表", notes="调用订单服务，查询订单列表")
    @ApiImplicitParam(name = "order", value = "订单", paramType = "body", required = false, dataType = "Order")
    @PostMapping("/list")
    public List<Order> listData(@Valid @RequestBody Order order, BindingResult bindingResult, HttpSession session){
        return orderClient.listData(order);
    }

    @ApiOperation(value = "新增订单", notes="调用订单服务，新增订单信息")
    @ApiImplicitParam(name = "order", value = "订单", paramType = "body", required = true, dataType = "Order")
    @PostMapping("/save")
//    @LcnTransaction(propagation = DTXPropagation.REQUIRED) //分布式事务注解
//    @Transactional //本地事务注解
    public String save(@Valid @RequestBody Order order, BindingResult bindingResult, HttpSession session){
        try {
            Product one = productClient.getOne(order.getProductId());
            Product product= new Product();
            product.setId(order.getProductId());
            order.setId(UuidUtil.getstring());
            order.setOrderId(40612204);
            product.setProductCount(one.getProductCount()-order.getCount());
            productClient.updateByProduct(product);
//            sender.send("------商品库存减少"+order.getCount()+"个，剩余"+product.getProductCount()+"个-------");
            orderClient.save(order);
//            sender.send("--------生成订单------");
            List list=new ArrayList();
            System.out.println(list.size());
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }

    }


}
